package remoteView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ExpandEvent;
import org.eclipse.swt.events.ExpandListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.ExpandBar;
import org.eclipse.swt.widgets.ExpandItem;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import com.cloudgarden.resource.SWTResourceManager;

import search.SearchTuple;
import configuration.Config;
import configuration.ConfigOperator;
import controller.CommandsExcuter;
import controller.CommandsExcuter.ChangeTagAlgoValidExcutor;
import controller.CommandsExcuter.GetInfoExcutor;
import controller.CommandsExcuter.GoToWebExcutor;
import controller.CommandsExcuter.OpenFileExcutor;


/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * this class represent the application screen of "CleverDropBox"
 * this screen is responsible of control the service and search files by tags
 */
public class AppScreen extends org.eclipse.swt.widgets.Composite {

	static private Display display;
	static private Shell shell;

	//menu bar items
	private Menu m;
	private MenuItem run;
	private Menu runMenu;
	private static MenuItem startMenuItem;
	private static MenuItem stopMenuItem;
	private MenuItem exitMenuItem;
	private MenuItem add;
	private Menu addMenu;
	private MenuItem sharedFolderMenuItem;
	private MenuItem plugMenuItem;
	private MenuItem folderMenuItem;
	private MenuItem help;
	private Menu helpmenu;
	private MenuItem settingMenuItem;
	private MenuItem toWebMenuItem;
	private MenuItem aboutMenuItem;

	//tool bar items
	private ToolBar bar;
	private static ToolItem stopButton;
	private static ToolItem startButton;
	private ToolItem addSharedFolderButton;
	private ToolItem addPluginButton;
	private ToolItem addFolderButton;

	//search items
	private Label searchTxt;
	private Text search;
	private Button searchButton;
	private Combo searchCombo;

	//setting items
	private Group settingGroup;
	private ArrayList<Button> settingCheckButtons;
	private  Button settingsButton;
	private  Button selectAllSettingButton;
	private Composite settingComp;
	private Button saveSettingButton;

	//tabs items
	private CTabFolder folder;
	private CTabItem firstTab;
	private Text text;
	private Table table;
	private TableColumn FileNamecolumn;
	private TableColumn FolderNamecolumn;
	private static Listener sortListener;

	//private  TableItem item2;

	//advanced search items
	private  ExpandBar expandBar;
	private  ExpandItem expandItem;
	private ScrolledComposite scrolledComp;
	private Composite comp;
	private  ArrayList<Button> checkButtonList;
	private ArrayList<String> tagsOptions;
	private MenuItem openMenuItem;
	private ToolItem openButton;
	static private Button toWebButton;
	static private PrintStream out;
	static private PrintStream err;
	/**
	 * constructor of the class
	 * @param parent
	 * @param style
	 */
	public AppScreen(Composite parent, int style) {
		super(new Shell(), style);
		//initGUI();
	}
	//main method for independents activation
	public static void main(String[] args) {
		//redirection of error and output to a log
	//	try {
			/*err = new PrintStream(new BufferedOutputStream(new FileOutputStream("errLog.txt")));
			out = new PrintStream(new BufferedOutputStream(new FileOutputStream("outLog.txt")));
			System.setErr(err);
			System.setOut(out);*/

			try {
				Config c = ConfigOperator.read("C:\\Program Files\\project\\ClientService\\Config.xml");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Display display = Display.getDefault();
			shell = new Shell(display);
			AppScreen inst = new AppScreen(shell, SWT.NULL);
			inst.initGUI();
			/*err.close();
			out.close();*/
		/*} catch (Exception e) {
			
			new ErrorMess();
			err.close();
			out.close();
			
		}*/
	}
	public static void openGUI() {
		
		Display display = Display.getDefault();
		Shell shell = new Shell(display);
		AppScreen inst = new AppScreen(shell, SWT.NULL);
		inst.initGUI();

	}
	/**
	 * initialize all GUI components
	 */
	public void initGUI() {
		//getting data of user from the service
		GetInfoExcutor getInfo=CommandsExcuter.getCommand().getGetInfo();
		getInfo.excute();
		//get the list of algorithms from the service 
		ArrayList<ArrayList<String>> algoList = getInfo.getRetVal();

		checkButtonList = new ArrayList<Button>();
		settingCheckButtons = new ArrayList<Button>();
		display = Display.getDefault();
		shell = new Shell(display);
		shell.setLayout(new FormLayout());
		shell.setText("CleverDropBox");
		bar = new ToolBar(shell,SWT.FLAT);
		searchTxt = new Label(shell, SWT.NONE);
		searchTxt.setText("Search:");
		FormData searchTxtData = new FormData();
		searchTxtData.left =  new FormAttachment(2);
		searchTxtData.top = new FormAttachment(bar,3);   
		searchTxt.setLayoutData(searchTxtData);  
		search = new Text(shell, SWT.BORDER);
		search.setSize(100, 1000);
		FormData searchData = new FormData();
		searchData.left =  new FormAttachment(searchTxt,5);
		searchData.top = new FormAttachment(bar,3);
		searchData.width=200;
		search.setLayoutData(searchData);
		//start listening button
		startButton = new ToolItem(bar,SWT.PUSH);
		startButton.setImage(SWTResourceManager.getImage("icons\\Button-Turn-On-icon.png"));//new Image(display, "icons\\Button-Turn-On-icon.png"));
		startButton.setWidth(15);
		startButton.setEnabled(false);
		startButton.setToolTipText("start service");
		startButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				startPush(evt);
			}
		});
		//stop listening button
		stopButton = new ToolItem(bar,SWT.PUSH);    
		stopButton.setImage(SWTResourceManager.getImage("icons\\Button-Turn-Off-icon.png"));//new Image(display, "icons\\Button-Turn-Off-icon.png"));
		stopButton.setToolTipText("Stop Service");
		stopButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				stopPush(evt);
			}
		});
		//add Shared Folder Button
		addSharedFolderButton = new ToolItem(bar,SWT.PUSH);
		addSharedFolderButton.setImage(SWTResourceManager.getImage("icons\\shareFolder.png"));//new Image(display, "icons\\shareFolder.png"));
		addSharedFolderButton.setToolTipText("Add new shared folder");
		addSharedFolderButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				addSharedFolderPush(evt);
			}
		});
		//add plug-in button
		addPluginButton = new ToolItem(bar,SWT.PUSH);
		addPluginButton.setImage(SWTResourceManager.getImage("icons\\USB-icon.png"));//new Image(display, "icons\\USB-icon.png"));
		addPluginButton.setToolTipText("Add new plug-in");
		addPluginButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				addPlugInPush(evt);
			}
		});

		//add regular folder button
		addFolderButton = new ToolItem(bar,SWT.PUSH);
		addFolderButton.setImage(SWTResourceManager.getImage("icons\\Folder-Add-icon.png"));//new Image(display, "icons\\Folder-Add-icon.png"));
		addFolderButton.setToolTipText("Add new folder");
		addFolderButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				addFolderPush(evt);
			}
		});
		//start listening button
		openButton = new ToolItem(bar,SWT.PUSH);
		openButton.setImage(SWTResourceManager.getImage("icons\\openFolder.png"));//new Image(display, "icons\\openFolder.png"));
		openButton.setWidth(15);
		openButton.setToolTipText("open CleverDropBox");
		openButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				openFolder(evt);
			}
		});
		//sets the upper bar settings
		FormData barData = new FormData();
		barData.left = new FormAttachment(0,1000,0);
		barData.top = new FormAttachment(0,1000,0);
		bar.setLayoutData(barData);

		//setting search options
		tagsOptions = new ArrayList<String>();
		FormData comboData = new FormData();
		comboData.left =  new FormAttachment(search,5);
		comboData.top = new FormAttachment(bar,3);
		searchCombo = new Combo(shell, SWT.DROP_DOWN | SWT.BORDER);
		searchCombo.setItems(tagsOptions.toArray(new String[0]));
		searchCombo.setText("Search By");
		searchCombo.setLayoutData(comboData);
		searchCombo.add("All");
		searchButton = new Button(shell, SWT.PUSH);
		searchButton.setImage(SWTResourceManager.getImage("icons\\Zoom-icon.png"));//new Image(display, "icons\\Zoom-icon.png"));
		searchButton.setToolTipText("start search");
		FormData searchButtonData = new FormData();
		searchButtonData.left =  new FormAttachment(searchCombo,5);
		searchButtonData.top = new FormAttachment(bar);
		searchButton.setLayoutData(searchButtonData);
		//creating menu bar
		m = new Menu(shell,SWT.BAR);

		// create a Run menu and add an exit item
		run = new MenuItem(m, SWT.CASCADE);
		run.setText("Run");
		runMenu = new Menu(shell, SWT.DROP_DOWN);
		run.setMenu(runMenu);
		startMenuItem = new MenuItem(runMenu, SWT.PUSH);
		startMenuItem.setText("&Run service\tCTRL+R");
		startMenuItem.setAccelerator(SWT.CTRL+'R');
		startMenuItem.setEnabled(false);
		startMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				startPush(evt);
			}
		});
		stopMenuItem = new MenuItem(runMenu, SWT.PUSH);
		stopMenuItem.setText("&Stop\tCTRL+S");
		stopMenuItem.setAccelerator(SWT.CTRL+'S');
		stopMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				stopPush(evt);
			}
		});
		new MenuItem(runMenu, SWT.SEPARATOR);
		exitMenuItem = new MenuItem(runMenu, SWT.PUSH);
		exitMenuItem.setText("Exit");
		exitMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				shell.dispose();
			}
		});

		// create an Add menu and add cut copy and paste items
		add = new MenuItem(m, SWT.CASCADE);
		add.setText("Add");
		addMenu = new Menu(shell, SWT.DROP_DOWN);
		add.setMenu(addMenu);
		folderMenuItem = new MenuItem(addMenu, SWT.PUSH);
		folderMenuItem.setText("&Folder\tCTRL+F");
		folderMenuItem.setAccelerator(SWT.CTRL+'F');
		folderMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				addFolderPush(evt);
			}
		});
		sharedFolderMenuItem = new MenuItem(addMenu, SWT.PUSH);
		sharedFolderMenuItem.setText("&Shared Folder\tCTRL+N");;
		sharedFolderMenuItem.setAccelerator(SWT.CTRL+'N');
		sharedFolderMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				addSharedFolderPush(evt);
			}
		});
		plugMenuItem = new MenuItem(addMenu, SWT.PUSH);
		plugMenuItem.setText("&Plug-in\tCTRL+P");
		plugMenuItem.setAccelerator(SWT.CTRL+'P');
		plugMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				addPlugInPush(evt);
			}
		});
		openMenuItem = new MenuItem(addMenu, SWT.PUSH);
		openMenuItem.setText("&Open CleverDropBox folder\tCTRL+O");
		openMenuItem.setAccelerator(SWT.CTRL+'O');
		openMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				openFolder(evt);

			}
		});


		// create a Help menu and add an about item
		help = new MenuItem(m, SWT.CASCADE);
		help.setText("Help");
		helpmenu = new Menu(shell, SWT.DROP_DOWN);
		help.setMenu(helpmenu);
		settingMenuItem = new MenuItem(helpmenu, SWT.PUSH);
		settingMenuItem.setText("&Settings\tCTRL+H");
		settingMenuItem.setAccelerator(SWT.CTRL+'H');
		settingMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				openSettingTab();
			}
		});
		toWebMenuItem = new MenuItem(helpmenu, SWT.PUSH);
		toWebMenuItem.setText("&Go to web site\tCTRL+W");
		toWebMenuItem.setAccelerator(SWT.CTRL+'W');
		toWebMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent evt) {
				GoToWebExcutor getInfo=CommandsExcuter.getCommand().getGoToWeb();
				getInfo.excute();
			}
		});
		new MenuItem(helpmenu, SWT.SEPARATOR);
		aboutMenuItem = new MenuItem(helpmenu, SWT.PUSH);
		aboutMenuItem.setText("&About\tCTRL+A");
		aboutMenuItem.setAccelerator(SWT.CTRL+'A');


		//create advanced search option
		expandBar = new ExpandBar(shell, SWT.NONE);
		expandItem = new ExpandItem(expandBar, SWT.NONE);
		expandItem.setText("Advanced Searching");
		final FormData expandBarData = new FormData();
		expandBarData.left =  new FormAttachment(0);
		expandBarData.top = new FormAttachment(search);
		expandBarData.right = new FormAttachment(100);
		expandBarData.height=20;
		expandBarData.width=700;
		expandBar.setBackground(display.getSystemColor(SWT.COLOR_GRAY));
		expandBar.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
		expandBar.setLayoutData(expandBarData);
		expandBar.setSpacing(0);
		scrolledComp = new ScrolledComposite(expandBar, SWT.V_SCROLL | SWT.H_SCROLL);
		scrolledComp.setLayout(new FillLayout());
		scrolledComp.setAlwaysShowScrollBars(true);
		comp = new Composite(scrolledComp, SWT.NONE);
		scrolledComp.setContent(comp);
		final FormData compData = new FormData();
		compData.left =  new FormAttachment(0);
		compData.right =  new FormAttachment(100);
		comp.setLayoutData(compData);
		comp.setLayout(new RowLayout(SWT.HORIZONTAL));
		expandItem.setHeight(105);
		expandItem.setControl(scrolledComp);

		folder = new CTabFolder(shell, SWT.BORDER);
		final FormData folder1LData = new FormData();
		folder1LData.left =  new FormAttachment(0);
		folder1LData.top = new FormAttachment(expandBar);
		folder1LData.bottom = new FormAttachment(90);
		folder1LData.right = new FormAttachment(100);
		folder1LData.width = 396;
		folder1LData.height = 254;
		folder.setLayoutData(folder1LData);
		folder.setSimple(false);
		//create listener to the expand Bar
		expandBar.addExpandListener(new ExpandListener() {

			@Override
			public void itemExpanded(ExpandEvent arg0) {
				expandBarData.height=130;
				searchCombo.setEnabled(false);
				search.setEnabled(false);
				//shell.pack();
				packAll();
			}

			@Override
			public void itemCollapsed(ExpandEvent arg0) {
				expandBarData.height=20;

				searchCombo.setEnabled(true);
				folder.layout(true);
				search.setEnabled(true);
				//shell.pack();
				packAll();
			}
		});

		firstTab = new CTabItem(folder, SWT.CLOSE);
		firstTab.setText("all files");
		firstTab.setShowClose(false);
		text = new Text(folder, SWT.MULTI);
		text.setText("Content for Item 1");
		firstTab.setControl(text);

		//add listener to search button
		searchButton.addListener(SWT.Selection, new Listener() {

			@Override
			public void handleEvent(Event arg0) {
				if (arg0.widget==searchButton){
					if(search.getText()!=""&&search.getEnabled()){
						search(search.getText());
						search.setText("");
					}
					else if(!search.getEnabled()){
						advancedSearch();
					}
				}
			}
		});
		//setting the search results composite
		int colorCount = 3; 
		Color[] colors = new Color[colorCount]; 
		colors[0] = display.getSystemColor(SWT.COLOR_TITLE_BACKGROUND); 
		colors[1] = display.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT); 
		colors[2] = colors[0]; 
		int[] percents = new int[colorCount - 1]; 
		percents[0] = 4; 
		percents[1] = 60; 
		folder.setSelectionBackground(colors, percents, true); 
		folder.setSelectionForeground(display.getSystemColor(SWT.COLOR_TITLE_FOREGROUND));
		folder.setSelection(firstTab);

		//defining setting button & his listeners
		{

			settingsButton = new Button(shell, SWT.PUSH);
			settingsButton.setImage(SWTResourceManager.getImage("icons\\Gear-icon.png"));//new Image(display, "icons\\Gear-icon.png"));
			settingsButton.setToolTipText("Settings");
			FormData settingsButtonLData = new FormData();
			settingsButtonLData.left =  new FormAttachment(0);
			settingsButtonLData.top = new FormAttachment(folder);
			settingsButton.setLayoutData(settingsButtonLData);

			settingsButton.addListener(SWT.Selection, new Listener(	) {
				@Override
				public void handleEvent(Event arg0) {
					openSettingTab();
				}


			});

			settingComp = new Composite(folder, SWT.NONE);
			settingComp.setLayout(new FormLayout());
			settingGroup = new Group(settingComp, SWT.SHADOW_IN);
			settingGroup.setText("Choose Tag Algorithm:");
			settingGroup.setLayout(new RowLayout(SWT.VERTICAL));
			FormData groupData = new FormData();
			groupData.left = new FormAttachment(0);
			groupData.top = new FormAttachment(0);
			settingGroup.setLayoutData(groupData);
			saveSettingButton = new Button(settingComp,SWT.PUSH);
			saveSettingButton.setText("Save");
			FormData settingSaveButtonData = new FormData();
			settingSaveButtonData.left = new FormAttachment(50);
			settingSaveButtonData.top = new FormAttachment(88);
			saveSettingButton.setLayoutData(settingSaveButtonData);
			saveSettingButton.addListener(SWT.Selection, new Listener() {

				@Override
				public void handleEvent(Event arg0) {
					//excute "change tag algorithm settings" command
					ChangeTagAlgoValidExcutor changeTagAlgo=CommandsExcuter.getCommand().getChangeTagAlgoValid();
					ArrayList<String> list = new ArrayList<String>();
					for(Button b : settingCheckButtons){
						if(b.getSelection()&&!b.getText().equals("Select/Deselect All"))
							list.add(b.getText());
					}
					changeTagAlgo.setPath(list);
					changeTagAlgo.excute();
					CTabItem item = folder.getSelection();
					item.dispose();
				}
			});
			selectAllSettingButton = new Button(settingGroup,SWT.CHECK);
			selectAllSettingButton.setText("Select/Deselect All");
			settingCheckButtons.add(selectAllSettingButton);
			selectAllSettingButton.setSelection(true);
			selectAllSettingButton.addListener(SWT.Selection, new Listener() {

				@Override
				public void handleEvent(Event arg0) {
					for(Button b : settingCheckButtons)
						b.setSelection(selectAllSettingButton.getSelection());
				}
			});

		}
		//defining button that link to CleverDropBox web site
		{
			toWebButton = new Button(shell, SWT.PUSH | SWT.CENTER);
			toWebButton.setImage(SWTResourceManager.getImage("icons\\website.png"));//new Image(display, "icons\\website.png"));
			FormData toWebButtonData = new FormData();
			toWebButtonData.left =  new FormAttachment(settingsButton);
			toWebButtonData.top = new FormAttachment(folder);
			toWebButton.setLayoutData(toWebButtonData);
			toWebButton.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					GoToWebExcutor getInfo=CommandsExcuter.getCommand().getGoToWeb();
					getInfo.excute();
				}

			});
		}
		KeyAdapter keyAdapter = new KeyAdapter() {
			public void keyReleased(KeyEvent event){
				String line = search.getText();
				if (event.keyCode=='\r'&&line!=""){
					// update the main screen

					if (searchCombo.getSelectionIndex()>-1){
						search(line);
						search.setText("");
					}
				}	

			}
		};
		search.addKeyListener(keyAdapter);
		////////////////////////////////////// Table ////////////////////////////

		//first tab
		table = new Table(folder, SWT.BORDER | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		FileNamecolumn = new TableColumn(table, SWT.NONE);
		FileNamecolumn.setText("File Name");
		FileNamecolumn.setWidth(100);
		FolderNamecolumn = new TableColumn(table, SWT.NONE);
		FolderNamecolumn.setText("Folder Name");
		FolderNamecolumn.setWidth(100);
		TableColumn sizeColumn = new TableColumn(table, SWT.NONE);
		sizeColumn.setText("Size");
		sizeColumn.setWidth(100);
		TableColumn dateColumn = new TableColumn(table, SWT.NONE);
		dateColumn.setText("Last Modefied");
		dateColumn.setWidth(100);
		TableColumn tagsColumn = new TableColumn(table, SWT.NONE);
		tagsColumn.setText("Tags");
		tagsColumn.setWidth(100);

		sortListener = new Listener() {
			public void handleEvent(Event e) {
				TableItem[] items = table.getItems();
				Collator collator = Collator.getInstance(Locale.getDefault());
				TableColumn column = (TableColumn) e.widget;
				int index = column == FileNamecolumn ? 0 : 1;
				int dir = table.getSortDirection();
				TableColumn sortColumn = table.getSortColumn();
				if (sortColumn == column) {
					dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
				} else {
					table.setSortColumn(column);
					dir = SWT.UP;
				}

				for (int i = 1; i < items.length; i++) {
					String value1 = items[i].getText(index);
					for (int j = 0; j < i; j++) {
						String value2 = items[j].getText(index);
						if (dir==SWT.UP){
							if (collator.compare(value1, value2) < 0) {
								String[] values = { items[i].getText(0), items[i].getText(1) };
								items[i].dispose();
								TableItem item = new TableItem(table, SWT.NONE, j);
								item.setText(values);
								items = table.getItems();
								break;
							}
						}
						else{
							if (collator.compare(value2, value1) < 0) {
								String[] values = { items[i].getText(0), items[i].getText(1) };
								items[i].dispose();
								TableItem item = new TableItem(table, SWT.NONE, j);
								item.setText(values);
								items = table.getItems();
								break;
							}
						}
					}
				}
				table.setSortColumn(column);
				table.setSortDirection(dir);
			}
		};
		FileNamecolumn.addListener(SWT.Selection, sortListener);
		FolderNamecolumn.addListener(SWT.Selection, sortListener);  

		table.setSortColumn(FileNamecolumn);
		table.setSortDirection(SWT.UP);

		table.addMouseListener(new MouseListener() {

			@Override
			public void mouseUp(MouseEvent arg0) {}

			@Override
			public void mouseDown(MouseEvent arg0) {}

			@Override
			public void mouseDoubleClick(MouseEvent arg0) {
				System.out.println(table.getSelection()[0].getText(0)+","+table.getSelection()[0].getText(1));
			}
		});

		firstTab.setControl(table);

		// add the tag algo to the GUI
		if(algoList!=null){
			for(ArrayList<String> list : algoList){
				searchCombo.setItem(0, list.get(0));
				addTagTypeToComp(list);
			}
		}
		ArrayList<String> list = new ArrayList<String>();
		for(Button b : checkButtonList)
			list.add(b.getText());
		CommandsExcuter.getCommand().getAdvancedSearch().setAdvancedSearch(list);
		CommandsExcuter.getCommand().getAdvancedSearch().excute();
		ArrayList<SearchTuple> tuples=CommandsExcuter.getCommand().getAdvancedSearch().getRetVal();
		if(tuples!=null){
			System.out.println("empty!!!!!!!!!!!!!!");
			for(SearchTuple s : tuples){
				TableItem item = new TableItem(table, SWT.NONE);
				item.setText(s.toArray());
			}
		}

		////////////////////////////////////////////////////////
		shell.setMenuBar(m);
		shell.pack();
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
	/*
	 * this method will be activated when "open CleverDropBox" button is pushed
	 */
	private void openFolder(SelectionEvent evt) {
		OpenFileExcutor openFileExcutor= CommandsExcuter.getCommand().getOpenFile();
		openFileExcutor.setPath("");
		openFileExcutor.excute();

	}
	/*
	 * this method will be activated when "add folder" button is pushed
	 */
	private void addFolderPush(SelectionEvent evt) {
		AddFolderBox.showGUI();

	}
	/*
	 * this method will be activated when "add plug in" button is pushed
	 */
	private void addPlugInPush(SelectionEvent evt) {
		AddPluginBox.showGUI();
		ArrayList<String> arr = AddPluginBox.getTagList();
		if(arr!=null){
			tagsOptions.add(arr.get(0));
			addTagTypeToComp(arr);
			searchCombo.add(arr.get(0));
		}

	}
	/*
	 * this method will be activated when "add shared folder" button is pushed
	 */
	private void addSharedFolderPush(SelectionEvent evt) {
		new AddSharedFolderBox();

	}
	/*
	 * this method will be activated when start button is pushed
	 */
	private static void startPush(SelectionEvent evt) {
		stopButton.setEnabled(true);
		startButton.setEnabled(false);
		startMenuItem.setEnabled(false);
		stopMenuItem.setEnabled(true);
		//excute "start" command
		CommandsExcuter.getCommand().getStart().excute();
	}
	/*
	 * this method will be activated when stop button is pushed
	 */
	private static void stopPush(SelectionEvent evt) {
		stopButton.setEnabled(false);
		startButton.setEnabled(true);
		startMenuItem.setEnabled(true);
		stopMenuItem.setEnabled(false);
		//excute "stop" command
		CommandsExcuter.getCommand().getStop().excute();

	}
	/*
	 * this method opens new tab to display all search results
	 */
	private void openNewTab(String line,ArrayList<SearchTuple> tuples){
		CTabItem item2 = new CTabItem(folder, SWT.CLOSE);
		item2.setText(line);	
		folder.setSelection(item2);  
		if(tuples==null){
			Text txt = new Text(folder, SWT.MULTI);
			txt.setText("There is no results for your search!");
			item2.setControl(txt);
			return;
		}
		final Table table  = new Table(folder, SWT.BORDER | SWT.FULL_SELECTION);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		TableColumn fileNameColumn = new TableColumn(table, SWT.NONE);
		fileNameColumn.setText("File Name");
		fileNameColumn.setWidth(100);
		TableColumn folderNameColumn = new TableColumn(table, SWT.NONE);
		folderNameColumn.setText("Folder Name");
		folderNameColumn.setWidth(100);
		TableColumn sizeColumn = new TableColumn(table, SWT.NONE);
		sizeColumn.setText("Size");
		sizeColumn.setWidth(100);
		TableColumn dateColumn = new TableColumn(table, SWT.NONE);
		dateColumn.setText("Last Modefied");
		dateColumn.setWidth(100);
		TableColumn tagsColumn = new TableColumn(table, SWT.NONE);
		tagsColumn.setText("Tags");
		tagsColumn.setWidth(100);
		if(tuples!=null){
			for(SearchTuple s : tuples){
				TableItem item = new TableItem(table, SWT.NONE);
				item.setText(s.toArray());
			}
		}
		//for sorting
		Listener newListener = new Listener() {
			public void handleEvent(Event e) {
				TableItem[] items = table.getItems();
				Collator collator = Collator.getInstance(Locale.getDefault());
				TableColumn column = (TableColumn) e.widget;
				TableColumn[] columns =table.getColumns();
				int index=0;
				for(int i=0;i<columns.length;i++){
					if(columns[i]==column){
						index=i;
						break;
					}
				}
				int dir = table.getSortDirection();
				TableColumn sortColumn = table.getSortColumn();
				if (sortColumn == column) {
					dir = dir == SWT.UP ? SWT.DOWN : SWT.UP;
				} else {
					table.setSortColumn(column);
					dir = SWT.UP;
				}
				for (int i = 1; i < items.length; i++) {
					String value1 = items[i].getText(index);
					for (int j = 0; j < i; j++) {
						String value2 = items[j].getText(index);
						if (dir==SWT.UP){
							if (collator.compare(value1, value2) < 0) {
								String[] values = { items[i].getText(0), items[i].getText(1) ,items[i].getText(2),items[i].getText(3),items[i].getText(4)};
								items[i].dispose();
								TableItem item = new TableItem(table, SWT.NONE, j);
								item.setText(values);
								items = table.getItems();
								break;
							}
						}
						else{
							if (collator.compare(value2, value1) < 0) {
								String[] values = { items[i].getText(0), items[i].getText(1) ,items[i].getText(2),items[i].getText(3),items[i].getText(4)};
								items[i].dispose();
								TableItem item = new TableItem(table, SWT.NONE, j);
								item.setText(values);
								items = table.getItems();
								break;
							}
						}
					}
				}
				table.setSortColumn(column);
				table.setSortDirection(dir);
			}};
			//add sort listener to all columns
			fileNameColumn.addListener(SWT.Selection,newListener );
			folderNameColumn.addListener(SWT.Selection,newListener );
			sizeColumn.addListener(SWT.Selection,newListener );
			dateColumn.addListener(SWT.Selection,newListener );
			tagsColumn.addListener(SWT.Selection,newListener );
			table.addMouseListener(new MouseListener() {
				@Override
				public void mouseUp(MouseEvent arg0) {}

				@Override
				public void mouseDown(MouseEvent arg0) {}

				@Override
				public void mouseDoubleClick(MouseEvent arg0) {
					Table tab=(Table)arg0.widget;
					String path=tab.getSelection()[0].getText(1)+"\\"+tab.getSelection()[0].getText(0);
					CommandsExcuter.getCommand().getOpenFile().setPath(path);
					CommandsExcuter.getCommand().getOpenFile().excute();
				}
			});
			item2.setControl(table);
			item2.getControl().setFocus();
	}
	/*
	 * this method is adding tag types to settings tab
	 */
	private void addTagTypeToComp(ArrayList<String> tagList){
		Group group = new Group(comp, SWT.SHADOW_IN);
		group.setText(tagList.get(0)+" : ");
		group.setLayout(new RowLayout(SWT.VERTICAL));
		for(int i=1;i<tagList.size();i++){
			String s= tagList.get(i);
			Button b = new Button(group, SWT.CHECK);
			b.setText(s);
			b.setSelection(true);
			checkButtonList.add(b);
		}
		scrolledComp.layout(true);
		comp.setSize(comp.computeSize(SWT.DEFAULT, SWT.DEFAULT));
		comp.layout(true);		
		Button newButton = new Button(settingGroup,SWT.CHECK);
		newButton.setText(tagList.get(0));
		newButton.setSelection(true);
		settingCheckButtons.add(newButton);
		settingComp.layout(true);
		settingGroup.layout(true);
		//shell.pack();
		packAll();
	}
	/*
	 * this method is opening new tab for settings
	 */
	private void openSettingTab() {
		CTabItem item2 = new CTabItem(folder, SWT.CLOSE);
		item2.setText("Setting");
		folder.setSelection(item2);
		item2.setControl(settingComp);
		item2.getControl().setFocus();
		//shell.pack();
		packAll();
	}
	/*
	 * this method search for tags in the file system
	 */
	private void search(String line){
		CommandsExcuter.getCommand().getSearch().setTag(line);
		ArrayList<String> tagTypeList = new ArrayList<String>();
		if(searchCombo.getSelectionIndex()==-1)
			return;

		if(searchCombo.getSelectionIndex()!=(searchCombo.getItemCount()-1))
			tagTypeList.add(searchCombo.getItem(searchCombo.getSelectionIndex()));		
		else{
			String[] items = searchCombo.getItems();
			for(int i=1;i<items.length;i++)
				tagTypeList.add(items[i]);

		}
		CommandsExcuter.getCommand().getSearch().setTagType(tagTypeList);
		CommandsExcuter.getCommand().getSearch().excute();
		ArrayList<SearchTuple> tuples=CommandsExcuter.getCommand().getSearch().getRetVal();
		openNewTab(line, tuples);
	}
	/*
	 * advanced search for multiply tags
	 */
	private void advancedSearch() {
		ArrayList<String> list = new ArrayList<String>();
		for(Button b : checkButtonList)
			if(b.getSelection())
				list.add(b.getText());
		CommandsExcuter.getCommand().getAdvancedSearch().setAdvancedSearch(list);
		CommandsExcuter.getCommand().getAdvancedSearch().excute();
		ArrayList<SearchTuple> tuples=CommandsExcuter.getCommand().getAdvancedSearch().getRetVal();
		openNewTab("Advanced Search", tuples);
	}
	private void packAll(){
		  startButton.setImage(SWTResourceManager.getImage("icons\\Button-Turn-On-icon.png"));
		  stopButton.setImage(SWTResourceManager.getImage("icons\\Button-Turn-Off-icon.png"));
		  addSharedFolderButton.setImage(SWTResourceManager.getImage("icons\\shareFolder.png"));
		  addPluginButton.setImage(SWTResourceManager.getImage("icons\\USB-icon.png"));
		  openButton.setImage(SWTResourceManager.getImage("icons\\openFolder.png"));
		  addFolderButton.setImage(SWTResourceManager.getImage("icons\\Folder-Add-icon.png"));
		  searchButton.setImage(SWTResourceManager.getImage("icons\\Zoom-icon.png"));
		  settingsButton.setImage(SWTResourceManager.getImage("icons\\Gear-icon.png"));
		  toWebButton.setImage(SWTResourceManager.getImage("icons\\website.png"));
		  shell.pack();
		 }

}

